package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleTemplateService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
public class ArticleTempateServiceImpl implements ArticleTemplateService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;



    /**
     * 生成模板页面并上传到minio
     * @param apArticle 文章对象
     * @param context 文章内容
     * @return 上传后模板网址的路径
     */
    @Override
    @Async // 异步调用
    public String buildArticleTemplateToMinIO(ApArticle apArticle, String context) {

        String path = "";
        //1.获取文章内容
        Long articleId = apArticle.getId();
        ApArticleContent apArticleContent =
                apArticleContentMapper.selectOne(
                        Wrappers.<ApArticleContent>lambdaQuery()
                                .eq(ApArticleContent::getArticleId, articleId));

        if(apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())){
            try {
                //2.文章内容通过freemarker生成html文件
                StringWriter out = new StringWriter();
                Template template = configuration.getTemplate("article.ftl");

                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(apArticleContent.getContent()));

                template.process(params, out);// 生成模板页面
                InputStream is = new ByteArrayInputStream(out.toString().getBytes());

                //3.把html文件上传到minio中
                path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

                //4.修改ap_article表，保存static_url字段
                ApArticle article = new ApArticle();
                article.setId(apArticleContent.getArticleId());
                article.setStaticUrl(path);
                apArticleMapper.updateById(article);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            }

        }

        //===============================================

        //发送消息，创建索引
        createArticleESIndex(apArticle,apArticleContent.getContent(),path);
        //===============================================

        return path;
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 送消息，创建索引
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }
}
